package com.kexun.mvc.servlet;

import com.alibaba.fastjson.JSON;
import com.kexun.annotation.ResponseBody;
import com.kexun.mvc.container.Containers;
import com.kexun.mvc.listen.InitMapping;
import com.kexun.mvc.resolvers.BaseResolver;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * @author KEXUN
 */
public class WebServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        Enumeration<String> parameterNames = req.getParameterNames();
        String contextPath = req.getServletPath();
        System.out.println(contextPath);
        Method method = Containers.mappingMethods.get(contextPath);
        if (method == null) {
            resp.sendError(404, "页面不存在");
        } else {
            String contentType = req.getContentType();
            String method1 = req.getMethod();
            System.out.println("method:" + method1 + " contentType:" + contentType);
            try {
                Object o = method.getDeclaringClass().newInstance();
                Parameter[] parameters = method.getParameters();
                ArrayList<Object> params = new ArrayList<>();
                for (Parameter parameter : parameters) {
                    Object o2 = null;
                    List<BaseResolver> resolvers = Containers.resolvers;
                    for (BaseResolver resolver : resolvers) {
                        if (resolver.supportsParameter(parameter)) {
                            o2 = resolver.resolveArgument(parameter, req, resp);
                            break;
                        }
                    }

//                    if (parameter.getType().isAssignableFrom(String.class)) {
//                        o2 = req.getParameter(name).toString();
//                    } else if (parameter.getType().isAssignableFrom(int.class)) {
//                        o2 = Integer.parseInt(req.getParameter(name));
//                    } else if (parameter.getType().isAssignableFrom(req.getClass())) {
//                        o2 = req;
//                    } else if (parameter.getType().isAssignableFrom(resp.getClass())) {
//                        o2 = resp;
//                    } else if (parameter.getType().isAssignableFrom(req.getSession().getClass())) {
//                        o2 = req.getSession();
//                    } else {
//                        o2 = parameter.getType().newInstance();
//                        while (parameterNames.hasMoreElements()) {
//                            String s = parameterNames.nextElement();
//                            String parameter1 = req.getParameter(s);
//                            BeanUtils.setProperty(o2, s, parameter1);
//                        }
//                    }
                    params.add(o2);

                }
                Object invoke = method.invoke(o, params.toArray());
                if (invoke != null) {
                    ResponseBody annotation = method.getAnnotation(ResponseBody.class);
                    if (annotation != null) {
                        if (invoke instanceof String) {
                            resp.setContentType("text/html");
                            resp.setCharacterEncoding("UTF-8");
                            // 获取PrintWriter对象
                            PrintWriter out = resp.getWriter();
                            out.print(invoke);
                            // 释放PrintWriter对象
                            out.flush();
                            out.close();
                        } else {
                            resp.setContentType("application/json; charset=utf-8");
                            resp.setCharacterEncoding("UTF-8");
                            // 获取PrintWriter对象
                            PrintWriter out = resp.getWriter();
                            out.print(JSON.toJSONString(invoke));
                            // 释放PrintWriter对象
                            out.flush();
                            out.close();
                        }

                    } else {
                        if (invoke instanceof String) {
                            RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/" + invoke + ".jsp");
                            dispatcher.forward(req, resp);
                        } else {
                            new RuntimeException("返回值不是String类型 且没有@ResponseBody注解");
                        }
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }


}
